<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据编号">
              <a-input placeholder="请输入单据编号" v-model="queryParam.patternId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料编码">
              <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="物料名称">
                <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('版样管理')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <a-tabs v-model="activeKey" @change="handleChangeTab">
      <a-tab-pane v-if="false" key="notGenerated" tab="暂存中"  force-render>
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="sign" slot-scope="text, record">
              <div>{{record.sign+record.year+record.productionOrder+record.packagingForm+record.packagingSpecifications+record.version}}</div>
            </span>

            <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical"></a-divider>
              <!--<a @click="relationAct(record)">关联流程</a> -->
<!--              <act-apply-btn-->
<!--                @success="handleChangeTab"-->
<!--                :data-id="record.id"-->
<!--                :serviceName="serviceName"-->
<!--                :variables="record"-->
<!--              ></act-apply-btn>-->
              <a-button type="link" @click="applySubmit(record.id,record)" :loading="submitLoading">提交申请</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane v-if="false" key="needEdit" tab="需修改"  force-render>
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="sign" slot-scope="text, record">
              <div>{{record.sign+record.year+record.productionOrder+record.packagingForm+record.packagingSpecifications+record.version}}</div>
            </span>

            <span slot="action" slot-scope="text, record">
           <a v-if="record.status < 0" @click="handleEdit(record)">编辑</a>

          <a-divider v-if="record.status < 0"  type="vertical" />
              <act-apply-btn
                v-show="record.actStatus == '撤回'"
                @success="handleChangeTab"
                :data-id="record.id"
                :serviceName="serviceName"
                :variables="record"
              ></act-apply-btn>
              <a v-if="record.actStatus != '撤回'" @click="handleStop(record)">取消申请</a>
              <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
              <a-divider type="vertical" />
         <a @click="handleDetail(record)">详情</a>
              <!--          <a-dropdown>
                          <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                          <a-menu slot="overlay">
                            <a-menu-item>
                              <a @click="handleDetail(record)">详情</a>
                            </a-menu-item>
                            <a-menu-item>
                              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                                <a>删除</a>
                              </a-popconfirm>
                            </a-menu-item>
                          </a-menu>
                        </a-dropdown>-->
        </span>

          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane v-if="false" key="approving" tab="审核中"  force-render>
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="sign" slot-scope="text, record">
              <div>{{record.sign+record.year+record.productionOrder+record.packagingForm+record.packagingSpecifications+record.version}}</div>
            </span>

            <span slot="action" slot-scope="text, record">
<!--          <a @click="handleEdit(record)">编辑</a>-->
          <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />

               <a @click="handleDetail(record)">详情</a>
              <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <a v-if="record.actStatus != '撤回'" @click="handleStop(record)">取消申请</a>
              <!--          <a-dropdown>
                          <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                          <a-menu slot="overlay">
                            <a-menu-item>
                              <a @click="handleDetail(record)">详情</a>
                            </a-menu-item>
                            <a-menu-item>
                              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                                <a>删除</a>
                              </a-popconfirm>
                            </a-menu-item>
                          </a-menu>
                        </a-dropdown>-->
        </span>

          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane key="approved" tab="已审批" force-render>
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="sign" slot-scope="text, record">
              <div>{{record.sign+record.year+record.productionOrder+record.packagingForm+record.packagingSpecifications+record.version}}</div>
            </span>

            <span slot="action" slot-scope="text, record">
<!--          <a @click="handleEdit(record)">编辑</a>-->

          <act-historic-detail-btn v-if='record.flowFlag!=1':data-id="record.id"></act-historic-detail-btn>
          <a-divider v-if='record.flowFlag!=1' type="vertical" />
         <a @click="handleDetail(record)">详情</a>
              <!--          <a-dropdown>
                          <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                          <a-menu slot="overlay">
                            <a-menu-item>
                              <a @click="handleDetail(record)">详情</a>
                            </a-menu-item>
                            <a-menu-item>
                              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                                <a>删除</a>
                              </a-popconfirm>
                            </a-menu-item>
                          </a-menu>
                        </a-dropdown>-->
        </span>

          </a-table>
        </div>
      </a-tab-pane>

    </a-tabs>

    <crm-pattern-management-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CrmPatternManagementModal from './modules/CrmPatternManagementModal'
import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import {filterObj} from "@/utils/util";
import {getAction,postAction} from "@api/manage";
import ActApplyBtn from '@views/flowable/components/ActApplyBtn.vue'
import ActCancelBtn from '@views/flowable/components/ActCancelBtn.vue'
import ActHandleBtn from '@views/flowable/components/ActHandleBtn.vue'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'
import {stopProcess} from "@views/flowable/api/process";
import { definitionStartByDataId, isFirstInitiator, deleteActivityAndJoin } from '@views/flowable/api/definition'
import { todoListNew } from '@views/flowable/api/todo'
import {parseTime} from "@/utils";

export default {
  name: "CrmPatternManagementList",
  mixins:[JeecgListMixin],
  components: {
    CrmPatternManagementModal,
    ActApplyBtn,
    ActCancelBtn,
    ActHandleBtn,
    ActHistoricDetailBtn,
  },
  data () {
    return {
      description: '版样管理管理页面',
      activeKey:'approved',
      serviceName: 'patternManagementService',
      submitLoading:false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'单据编号',
          align:"center",
          dataIndex: 'patternId'
        },

        {
          title:'板样代码',
          align:"center",
          dataIndex: 'sign',
          scopedSlots: { customRender: 'sign' },
        },
        {
          title:'物料编码',
          align:"center",
          dataIndex: 'materialCode'
        },
        {
          title:'物料名称',
          align:"center",
          dataIndex: 'materialName'
        },
        {
          title:'规格型号',
          align:"center",
          dataIndex: 'spec'
        },
        {
          title: '制单人',
          align: 'center',
          dataIndex: 'createBy_dictText',
        },
        {
          title: '制单部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText',
        },
        {
          title: '制单时间',
          align: 'center',
          dataIndex: 'createTime',
          sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' },
        }
      ],
      url: {
        list: "/pattern/crmPatternManagement/list",
        delete: "/pattern/crmPatternManagement/delete",
        deleteBatch: "/pattern/crmPatternManagement/deleteBatch",
        exportXlsUrl: "/pattern/crmPatternManagement/exportXls",
        importExcelUrl: "pattern/crmPatternManagement/importExcel",
        editMain: "/pattern/crmPatternManagement/editMain",
      },
      dictOptions:{},
      superFieldList:[],
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    applySubmit(dataId,variables){
      if(variables.flowFlag=='1'){

        variables.status = 999
        postAction(this.url.editMain,variables).then((res)=>{
          this.$message.success("提交成功")
          this.handleChangeTab()
        })
        return;
      }
      if (dataId && dataId.length < 1) {
        this.error = '必须传入参数dataId'
        this.$message.error(this.error)
        return
      }
      if (this.serviceName && this.serviceName.length < 1) {
        this.error = '必须传入参数serviceName'
        this.$message.error(this.error)
        return
      } else {
        this.error = ''
      }
      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      this.submitLoading = true

      var params = Object.assign(
        {
          dataId: dataId,
        },
        variables
      )
      definitionStartByDataId(dataId, this.serviceName, params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)


          }
          }).finally(() => {
          this.submitLoading = false;
          this.handleChangeTab()
        }
      )

    },
    initDictConfig(){
    },
    handleStop(row) {
      const params = {
        instanceId: row.processInstanceId,
      }
      stopProcess(params).then((res) => {
        this.$message.success(res.message)
        this.handleChangeTab()
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
      // param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    loadData(arg,status) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      /*      if(this.activeKey!='notGenerated'){
              this.handleChangeTab()
              return;
            }*/
      if(status==null){
        this.handleChangeTab()
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      params.status = status
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result;
          this.dataSourceBack=this.dataSource
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    handleChangeTab() {
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadData(1,-2)
          break
        case 'needEdit':
          this.loadData(1,-1)
          break
        case 'approving':
          this.loadData(1,0)
          break
        case 'approved':
          this.loadData(1,999)
          break
        default:
          break
      }
    },
    getSuperFieldList(){
      let fieldList=[];
      fieldList.push({type:'string',value:'patternId',text:'单据编号',dictCode:''})
      fieldList.push({type:'string',value:'flowFlag',text:'审批流程',dictCode:'pattern_flow_flag'})
      fieldList.push({type:'string',value:'materialCode',text:'物料编码',dictCode:''})
      fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
      fieldList.push({type:'string',value:'spec',text:'规格型号',dictCode:''})
      fieldList.push({type:'string',value:'unit',text:'单位',dictCode:''})
      fieldList.push({type:'date',value:'revisionTime',text:'改版时间'})
      fieldList.push({type:'string',value:'sign',text:'标识',dictCode:''})
      fieldList.push({type:'string',value:'year',text:'年份(2位)',dictCode:''})
      fieldList.push({type:'string',value:'productionOrder',text:'排产单号(4位)',dictCode:''})
      fieldList.push({type:'string',value:'packagingForm',text:'包装形式(1位)',dictCode:''})
      fieldList.push({type:'string',value:'packagingSpecifications',text:'包装规格(2位)',dictCode:''})
      fieldList.push({type:'string',value:'version',text:'版本号(2位)',dictCode:''})
      fieldList.push({type:'Text',value:'revisedContent',text:'改版内容',dictCode:''})
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>